const express = require('express');
const router = express.Router();
const pool = require('../config/db');
const { logOperation } = require('./logs');

// 状态码定义
const CODE = {
  SUCCESS: 0,
  PARAM_ERROR: 1001,
  NOT_FOUND: 1002,
  SERVER_ERROR: 500,
  NO_PERMISSION: 1003
};

/**
 * 获取系统设置
 * GET /api/system/settings
 */
router.get('/list', async (req, res) => {
  try {
    // 获取所有系统设置
    const [settings] = await pool.execute(
      'SELECT * FROM system_settings WHERE status = "enabled" ORDER BY category, sort_order'
    );

    // 按类别组织设置
    const settingsByCategory = settings.reduce((acc, setting) => {
      if (!acc[setting.category]) {
        acc[setting.category] = [];
      }
      acc[setting.category].push(setting);
      return acc;
    }, {});

    res.json({
      code: CODE.SUCCESS,
      message: '获取系统设置成功',
      data: settingsByCategory
    });
  } catch (error) {
    console.error('获取系统设置错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 更新系统设置
 * PUT /api/system/settings
 */
router.put('/save', async (req, res) => {
  try {
    const { settings } = req.body;

    if (!Array.isArray(settings)) {
      return res.json({
        code: CODE.PARAM_ERROR,
        message: '参数格式错误'
      });
    }

    // 开启事务
    const connection = await pool.getConnection();
    await connection.beginTransaction();

    try {
      for (const setting of settings) {
        const { key, value } = setting;
        await connection.execute(
          'UPDATE system_settings SET value = ?, update_time = NOW() WHERE setting_key = ?',
          [value, key]
        );
      }

      await connection.commit();

      // 记录操作日志
      await logOperation(
        // req.user.userId,
        // 'update',
        // '系统设置',
        // '更新系统设置',
        // req.ip,
        // req.headers['user-agent']
        {
          userId: req.user.userId,
          type: 'update',
          module: '系统设置',
          details: '更新系统设置',
          ipAddress: req.ip,
          userAgent: req.headers['user-agent']
        }
      );

      res.json({
        code: CODE.SUCCESS,
        message: '更新系统设置成功'
      });
    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  } catch (error) {
    console.error('更新系统设置错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 获取字典数据
 * GET /api/system/dict/:type
 */
router.get('/dict/:type', async (req, res) => {
  try {
    const { type } = req.params;

    const [items] = await pool.execute(
      'SELECT * FROM system_dict WHERE dict_type = ? AND status = "enabled" ORDER BY sort_order',
      [type]
    );

    res.json({
      code: CODE.SUCCESS,
      message: '获取字典数据成功',
      data: items
    });
  } catch (error) {
    console.error('获取字典数据错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 更新字典数据
 * PUT /api/system/dict/:type
 */
router.put('/dict/:type', async (req, res) => {
  try {
    const { type } = req.params;
    const { items } = req.body;

    if (!Array.isArray(items)) {
      return res.json({
        code: CODE.PARAM_ERROR,
        message: '参数格式错误'
      });
    }

    // 开启事务
    const connection = await pool.getConnection();
    await connection.beginTransaction();

    try {
      // 先删除原有数据
      await connection.execute(
        'DELETE FROM system_dict WHERE dict_type = ?',
        [type]
      );

      // 插入新数据
      for (const item of items) {
        await connection.execute(
          `INSERT INTO system_dict 
           (dict_type, dict_key, dict_value, description, sort_order, status)
           VALUES (?, ?, ?, ?, ?, ?)`,
          [type, item.key, item.value, item.description, item.sortOrder, 'enabled']
        );
      }

      await connection.commit();

      // 记录操作日志
      await logOperation(
        // req.user.userId,
        // 'update',
        // '系统设置',
        // `更新字典数据：${type}`,
        // req.ip,
        // req.headers['user-agent']
        {
          userId: req.user.userId,
          type: 'update',
          module: '系统设置',
          details: `更新字典数据：${type}`,
          ipAddress: req.ip,
          userAgent: req.headers['user-agent']
        }
      );

      res.json({
        code: CODE.SUCCESS,
        message: '更新字典数据成功'
      });
    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  } catch (error) {
    console.error('更新字典数据错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 获取所有字典类型
 * GET /api/system/dict-types
 */
router.get('/dict-types', async (req, res) => {
  try {
    const [types] = await pool.execute(
      'SELECT DISTINCT dict_type, COUNT(*) as item_count FROM system_dict GROUP BY dict_type'
    );

    res.json({
      code: CODE.SUCCESS,
      message: '获取字典类型成功',
      data: types
    });
  } catch (error) {
    console.error('获取字典类型错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 获取系统参数配置
 * GET /api/system/params
 */
router.get('/params', async (req, res) => {
  try {
    const [params] = await pool.execute(
      'SELECT * FROM system_params WHERE status = "enabled" ORDER BY category, param_key'
    );

    // 按类别组织参数
    const paramsByCategory = params.reduce((acc, param) => {
      if (!acc[param.category]) {
        acc[param.category] = [];
      }
      acc[param.category].push(param);
      return acc;
    }, {});

    res.json({
      code: CODE.SUCCESS,
      message: '获取系统参数成功',
      data: paramsByCategory
    });
  } catch (error) {
    console.error('获取系统参数错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 更新系统参数
 * PUT /api/system/params
 */
router.put('/params', async (req, res) => {
  try {
    const { params } = req.body;

    if (!Array.isArray(params)) {
      return res.json({
        code: CODE.PARAM_ERROR,
        message: '参数格式错误'
      });
    }

    // 开启事务
    const connection = await pool.getConnection();
    await connection.beginTransaction();

    try {
      for (const param of params) {
        const { key, value, description } = param;
        await connection.execute(
          `UPDATE system_params 
           SET param_value = ?, description = ?, update_time = NOW()
           WHERE param_key = ?`,
          [value, description, key]
        );
      }

      await connection.commit();

      // 记录操作日志
      await logOperation(
        // req.user.userId,
        // 'update',
        // '系统设置',
        // '更新系统参数',
        // req.ip,
        // req.headers['user-agent']
        {
          userId: req.user.userId,
          type: 'update',
          module: '系统设置',
          details: '更新系统参数',
          ipAddress: req.ip,
          userAgent: req.headers['user-agent']
        }
      );

      res.json({
        code: CODE.SUCCESS,
        message: '更新系统参数成功'
      });
    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  } catch (error) {
    console.error('更新系统参数错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 获取系统通知设置
 * GET /api/system/notifications
 */
router.get('/notifications', async (req, res) => {
  try {
    const [settings] = await pool.execute(
      'SELECT * FROM notification_settings WHERE status = "enabled"'
    );

    res.json({
      code: CODE.SUCCESS,
      message: '获取通知设置成功',
      data: settings
    });
  } catch (error) {
    console.error('获取通知设置错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 更新系统通知设置
 * PUT /api/system/notifications
 */
router.put('/notifications', async (req, res) => {
  try {
    const { settings } = req.body;

    if (!Array.isArray(settings)) {
      return res.json({
        code: CODE.PARAM_ERROR,
        message: '参数格式错误'
      });
    }

    // 开启事务
    const connection = await pool.getConnection();
    await connection.beginTransaction();

    try {
      for (const setting of settings) {
        const { type, enabled, channels } = setting;
        await connection.execute(
          `UPDATE notification_settings 
           SET enabled = ?, channels = ?, update_time = NOW()
           WHERE notification_type = ?`,
          [enabled ? 1 : 0, JSON.stringify(channels), type]
        );
      }

      await connection.commit();

      // 记录操作日志
      await logOperation(
       
        {
          userId: req.user.userId,
          type: 'update',
          module: '系统设置',
          details: '更新通知设置',
          ipAddress: req.ip,
          userAgent: req.headers['user-agent']
        }
      );

      res.json({
        code: CODE.SUCCESS,
        message: '更新通知设置成功'
      });
    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  } catch (error) {
    console.error('更新通知设置错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

module.exports = router;
